<template>
  <div class="analysis-editor">
    <div v-for="(item, index) in analysisModel" :key="index" class="analysis-item">
      <!-- Text Analysis -->
      <el-input
        v-if="item.type === 'text'"
        v-model="item.content"
        type="textarea"
        :rows="3"
        placeholder="请输入文字解析"
      />
      <!-- Image Analysis -->
      <div v-if="item.type === 'image'" class="media-uploader">
         <el-upload
            :http-request="uploadRequest"
            :show-file-list="false"
            :on-success="(res) => handleUploadSuccess(res, index)"
            :on-error="handleUploadError"
            :before-upload="beforeImageUpload"
          >
            <img v-if="item.content" :src="item.content" class="media" />
            <el-icon v-else class="uploader-icon"><Plus /></el-icon>
          </el-upload>
      </div>
      <!-- Video Analysis -->
      <div v-if="item.type === 'video'" class="media-uploader">
         <el-upload
            :http-request="uploadRequest"
            :show-file-list="false"
            :on-success="(res) => handleUploadSuccess(res, index)"
            :on-error="handleUploadError"
            :before-upload="beforeVideoUpload"
          >
            <video v-if="item.content" :src="item.content" class="media" controls></video>
            <el-icon v-else class="uploader-icon"><Plus /></el-icon>
          </el-upload>
      </div>
      <el-button @click="removeItem(index)" :icon="Delete" circle plain class="remove-btn"></el-button>
    </div>

    <div class="actions">
       <el-button @click="addItem('text')" :icon="Document">添加文字</el-button>
       <el-button @click="addItem('image')" :icon="Picture">添加图片</el-button>
       <el-button @click="addItem('video')" :icon="VideoPlay">添加视频</el-button>
    </div>
  </div>
</template>

<script setup>
import { Plus, Delete, Document, Picture, VideoPlay } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { uploadFile } from '@/api/file'

// Define v-model for analysis items
const analysisModel = defineModel('analysis', {
  type: Array,
  required: true,
});

// 使用自定义上传，走 axios 拦截器

// Resolve static resource URL based on env var (dev: plain domain; prod: empty string)
const staticEndpoint = (import.meta.env.VITE_STATIC_ENDPOINT || '').replace(/\/$/, '');
const resolveStaticUrl = (value) => {
  if (!value) return '';
  // Already absolute
  if (/^https?:\/\//i.test(value) || value.startsWith('//')) return value;
  const normalizedPath = value.startsWith('/') ? value : `/${value}`;
  return `${staticEndpoint}${normalizedPath}`;
};

const addItem = (type) => {
  analysisModel.value.push({
    type,
    content: '',
    sort: analysisModel.value.length,
  });
};

const removeItem = (index) => {
  analysisModel.value.splice(index, 1);
};

const handleUploadSuccess = (response, index) => {
  const url = response;
  if (url) {
    // 直接使用原始URL，不使用resolveStaticUrl处理
    // resolveStaticUrl仅用于前端显示，不应影响发送给后端的数据
    analysisModel.value[index].content = url;
    ElMessage.success('上传成功');
  } else {
    ElMessage.error('上传失败，未获取到文件地址');
  }
};

const handleUploadError = () => {
  // 由全局拦截器处理，这里不需要提示
  // ElMessage.error('上传失败，请重试');
};

// Element Plus 自定义上传钩子，返回 Promise，让组件内部统一触发 on-success/on-error（避免重复回调）
const uploadRequest = async (options) => {
  const { file } = options
  const formData = new FormData()
  formData.append('file', file)
  // 返回 axios 调用结果，交由组件触发 on-success/on-error
  return uploadFile(formData)
}

const beforeImageUpload = (rawFile) => {
  const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(rawFile.type)
  if (!isImage) {
    ElMessage.error('图片格式必须是 JPG/PNG/GIF 格式!')
    return false
  }
  const isLt10M = rawFile.size / 1024 / 1024 <= 10
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    return false
  }
  return true
}

const beforeVideoUpload = (rawFile) => {
  // const isVideo = ['video/mp4', 'video/webm', 'video/ogg'].includes(rawFile.type)
  // if (!isVideo) {
  //   ElMessage.error('视频格式必须是 MP4/WEBM/OGG 格式!')
  //   return false
  // }
  return true
}
</script>

<style scoped>
.analysis-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
}
.analysis-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  position: relative;
}
.remove-btn {
  margin-left: 10px;
}
.actions {
  margin-top: 10px;
}

.media-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: .2s;
}
.media-uploader .el-upload:hover {
  border-color: #409eff;
}
.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}
.media {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: contain;
}
</style>
